package com.basic.business.prodRel.service.impl;

import com.basic.business.common.constants.Constants;
import com.basic.business.common.redis.RedisCacheUtils;
import com.basic.business.prodRel.domain.TProdRelDetails;
import com.basic.business.prodRel.mapper.TProdRelDetailsMapper;
import com.basic.business.prodRel.service.ITProdRelDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品关系主表服务实现类
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TProdRelDetailsServiceImpl implements ITProdRelDetailsService {

    @Resource
    private TProdRelDetailsMapper detailMapper;

    /**
     * 项目启动时，初始化商品关系缓存
     */
    @PostConstruct
    public void init(){
        resetProdRelCache();
    }

    @Override
    public List<TProdRelDetails> getList() {
        return detailMapper.getList();
    }

    /**
     * 重置商品关系缓存
     */
    private void resetProdRelCache() {
        // 清空缓存
        RedisCacheUtils.clearCache(Constants.PROD_REL_REDIS_KEY + "*");
        // 加载缓存
        loadingProdRelCache();
    }

    /**
     * 加载商品关系缓存
     */
    private void loadingProdRelCache() {
        Map<String, List<TProdRelDetails>> prodRelMap = getList().stream().collect(Collectors.groupingBy(TProdRelDetails::getMainId));
        for (Map.Entry<String, List<TProdRelDetails>> entry : prodRelMap.entrySet()) {
            RedisCacheUtils.setCacheObject(Constants.PROD_REL_REDIS_KEY + entry.getKey(), entry.getValue());
        }
    }
}
